import React, {PureComponent} from 'react';
import {Editor} from 'react-draft-wysiwyg';
import {routerRedux, Link} from 'dva/router';
import {connect} from 'dva';
import Spec from './Spec';
import SpecList from './SpecList';
import SpecParams from './SpecParams';
import GroupAdd from './GroupAdd';
import Uploader from './Uploader';
import UploadVideo from './UploadVideo';
//import { EditorState } from 'draft-js';
import MyEditor from './UmEditor';
import GoodsModal from '../Sales/GoodsModal';
import {
    Form,
    Input,
    DatePicker,
    Select,
    Button,
    Card,
    InputNumber,
    Radio,
    Icon,
    Tooltip,
    Upload,
    Divider,
    Row,
    Col,
    Checkbox,
    Table,
    notification,
    message,
    Carousel,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import G from '../../utils/g';
import styles from './addgoods.less';
import Authorized from '../../utils/Authorized';
import {getAuthority} from '../../utils/authority';
import logo from '../../assets/logo.png';

const FormItem = Form.Item;
const {Option} = Select;
const {RangePicker} = DatePicker;
const {TextArea} = Input;


const linkGoodsTip = [
    '随机选择相同分类商品显示',
    '实时显示最新商品',
    '实时显示销量最高的商品',
    '自定义显示商品'
]

// @connect(({ loading }) => ({
//   submitting: loading.effects['form/submitRegularForm'],
// }))
@connect(state => ({
    addGoods: state.addGoods,
}))
@Form.create()



export default class BasicForms extends PureComponent {

    postData = {
        imgs: []
    };

    state = {
        paramsData: [],  //规格参数
        specData: [], //商品规格
        visibleGroupForm: false,
        clearImgs: false,
        selectedGoods: [], //选中的相关商品
        banner: [], //上传的banner图片，用于即时显示
        modalVisible: false,
        minPrice: 0, //显示的最小价格
        content: '', //详情内容
    };

    componentWillUnmount() {
        const {dispatch} = this.props;
        dispatch({
            type: 'addGoods/clear',
        });
    }

    componentDidMount() {
        const {dispatch, location} = this.props;
        this.id = G.getUrlValue('id', location.search);
        if (typeof this.id != 'undefined') {
            dispatch({
                type: 'addGoods/getGoodsDetail',
                payload: {
                    id: this.id
                }
            }).then(()=> {
                const goods = {...this.props.addGoods.goods};

                let newState = {};
                if (goods.specs) {
                    newState.specData = goods.specs;

                }
                if (goods.spec_params) {
                    newState.paramsData = goods.spec_params;
                }
                if (goods.link_info.link_goods) {
                    newState.selectedGoods = goods.link_info.link_goods;
                }
                newState.banner = goods.imgs;
                if (goods.content) {
                    newState.content = goods.content;
                }
                console.log('newState', newState);
                this.setState(newState);
                this.postData = goods;
                //除掉表单绑定数据，防止提交时被覆盖
                delete this.postData.categoryId;
                delete this.postData.desc;
                delete this.postData.groups;
                delete this.postData.line_price;
                delete this.postData.price;
                delete this.postData.name;
                delete this.postData.status;
                delete this.postData.settlement_price;
                delete this.postData.stock;
                delete this.postData.video;
                delete this.postData.link_info.model;
                delete this.postData.order_weight;
            });
        }
        dispatch({
            type: 'addGoods/getCategory',
        });
        dispatch({
            type: 'addGoods/getGroup',
        });
    };

    componentWillReceiveProps(nextProps) {
        console.log(nextProps);
        if (nextProps.addGoods.link_goods != this.props.addGoods.link_goods) {
            this.setState({
                selectedGoods: nextProps.addGoods.link_goods
            });
        }
    }

    handleSubmit = e => {
        e.preventDefault();
        const {form, location} = this.props;
        console.log(form.getFieldValue('imgs'));
        form.validateFieldsAndScroll((err, values) => {
            console.log('values', values);
            console.log(this.postData);
            let linkGoodsInfo = {
                model: values.link_goods,
            }
            if (linkGoodsInfo.model == 3) {  //自定义关联商品
                linkGoodsInfo.link_goods = this.state.selectedGoods.map(v=>v.id);
            }
            let postData = {
                ...values,
                ...this.postData,
                specs: this.state.specData,
                link_info: linkGoodsInfo
            };
            // if (postData.specs_list && Array.isArray(postData.specs_list)) {
            //   postData.specs_list.forEach(v=> {
            //     v.freight = values.express;
            //   });
            // }
            if (G.getUrlValue('id')) {
                postData.id = G.getUrlValue('id', location.search);
            }

            if (postData.imgs == '') {
                message.error('商品图片不能为空');
                return;
            }
            if (postData.specs.length == 0) {  //无规格值时
                postData.specs_list = [{
                    sku: {},
                    price: postData.price,
                    stock: postData.stock,
                    settlement_price: postData.settlement_price
                }]
            }

            console.log('postData', postData);
            if (!err) {
                this.props.dispatch({
                    type: 'addGoods/saveGoods',
                    payload: postData,
                });
            }
        });
    };

    bindImgsChange = (file)=> {
        this.postData.imgs = [];
        file.forEach(v=> {
            this.postData.imgs.push(v.url)
        });
        this.setState({
            banner: this.postData.imgs
        });
        if (file.length == 0) {
            this.setState({
                clearImgs: true
            });
        }
        //console.log(this.postData);
    };

    bindVideoChange = (file)=> {
        this.props.dispatch({
            type: 'addGoods/saveVideo',
            payload: {
                url: file[0].url
            }
        });
        this.postData.video = file.length > 0 ? file[0].url : '';
    };

    bindSpcChange = (specData)=> {
        console.log(specData);
        this.setState({
            specData: specData
        });
    };

    bindSpecParamsChange = (data)=> {
        this.postData.spec_params = data;
        this.setState({
            paramsData: data
        });
    };

    bindMyEditorChange = (value)=> {
        this.postData.content = value;
        this.setState({
            content: value
        });
    };

    bindSpecListChange = (data)=> {
        //console.log('speclist',data);
        const {specData} = this.state;
        let minPrice = Infinity;
        let specsList = [];
        data.forEach(v=> {
            let sku = {};
            specData.forEach((val, j)=> {
                sku[val.name] = v[j]
            });
            specsList.push({
                sku: sku,
                price: v.price,
                stock: v.stock,
                settlement_price: v.settlement_price
            });
            if (v.price < minPrice) {
                minPrice = v.price
            } //计算出价格最小值 ，用于显示预览
        });
        this.setState({
            minPrice: minPrice
        });
        //console.log('specsList',specsList);
        this.postData.specs_list = specsList;
    };

    bindLinkGoods = (value)=> {  //只要select选择，则调用此方法
        console.log(value);
        if (value == -1 || value == 3) {
            this.setState({
                selectedGoods: []
            });
        }
        if (value == 3) {  //手动选择商品
            this.handleModalVisible(true);
        }
    }

    bindChangeLinkGoods = (value)=> {
        this.setState({  //默认清除已有选中的商品数据
            selectedGoods: []
        });
        let payload = {model: value};
        if (value == -1) {
            return false;
        }
        if (value == 3) {
            return false;
        }
        if (this.id) {
            payload.id = this.id;
        }
        const categoryId = this.props.form.getFieldValue('categoryId');
        if (value == 0) {
            if (categoryId) { //同分类
                payload.categoryId = categoryId
            } else {
                message.error('请先选择分类');
                return false;
            }
        }
        this.props.dispatch({
            type: 'addGoods/getLinkGoods',
            payload: payload
        });
    }

    bindCategoryChange = (value)=> {
        //分类改变时，相关分类商品也需要修改
        if (this.props.form.getFieldValue('link_goods') == 0) { //同分类
            this.props.dispatch({
                type: 'addGoods/getLinkGoods',
                payload: {
                    categoryId: value,
                    model: 0
                }
            });
        }
    }

    handleModalVisible = flag => {
        this.setState({
            modalVisible: !!flag,
        });
    };

    changeSelectedGoods = (goods)=> {  //从弹框中获取到选中商品的
        console.log("goods", goods);
        if (goods.length >= 4) { //最多只能选择四个商品
            this.handleModalVisible(false);
        }
        this.setState({
            selectedGoods: goods
        });
    };


    removeSelected = (id)=> {  //移除选中的商品

        if (typeof id == 'undefined') {
            console.error('被移除的商品ID为空');
            return false;
        }
        let selectedGoods = [...this.state.selectedGoods];
        const result = selectedGoods.filter(v => v.id != id);
        //console.log('selectedGoods',selectedGoods, result);
        this.setState({
            selectedGoods: result
        });

    };

    render() {
        const {addGoods : {category = [], group, goods}, dispatch} = this.props;
        const {paramsData, specData, clearImgs, selectedGoods, modalVisible, banner, minPrice, content} = this.state;
        const {getFieldDecorator, getFieldValue} = this.props.form;

        //console.log('selectedGoods', selectedGoods);

        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 4},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 12},
                md: {span: 15},
            },
        };

        const formDetailItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 4},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 12},
                md: {span: 20},
            },
        };

        const submitFormLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 10, offset: 7},
            },
        };

        let imgsFileList = [];
        if (!clearImgs && Array.isArray(goods.imgs)) {
            imgsFileList = goods.imgs.map(v=> {
                const uid = G.uuid(16);
                return {
                    uid: uid,
                    name: uid,
                    status: 'done',
                    url: v,
                }
            });
        }

        let videoFileList = [];
        if (goods.video) {
            videoFileList.push({
                uid: G.uuid(16),
                status: 'done',
                url: goods.video
            });
        }

        if (goods.specs && goods.specs.length == 0) {
            goods.price = goods.specs_list[0].price;
            goods.stock = goods.specs_list[0].stock;
            goods.settlement_price = goods.specs_list[0].settlement_price;
        }

        let columns = [
            {
                title: '图片',
                dataIndex: 'imgs',
                render(val) {
                    return <img src={`${val[0]}?imagediv2/1/w/50`} width="50" height="50"/>;
                },
            },
            {
                title: '名称',
                dataIndex: 'name',
            },
            {
                title: '库存',
                dataIndex: 'stock_count',
                align: 'right',
                render: val => `${val || 0}`,
            },
            {
                title: '价格',
                dataIndex: 'min_price',
                align: 'right',
                render: val => `${val || 0}元`,
            },

        ];
        if (getFieldValue('link_goods') == 3) {
            columns.push({
                title: '操作',
                render: (text, records)=> {
                    return <a onClick={()=> {
                        this.removeSelected(text.id)
                    }}>移除</a>
                }
            });
        }

        // 商品状态：管理员新增，默认为上架、修改默认为当前状态
        //          商家新增，默认为提交审核、修改默认也为提交审核
        // let status = getAuthority() == 'admin' ? 1 : 3;
        // if( goods.status &&  getAuthority() == 'admin' ){
        //   status = goods.status;
        // }
        // const status = getAuthority() == 'admin' ? (goods.status || 1 ): 3;

        // console.log('specData', specData);
        return (
            <div>
                <Card bordered={false}>
                    <Row>
                        <Col md={7}>
                            实时预览
                            <div style={{
                                height: '640px',
                                'overflowY': 'auto',
                                border: '1px solid #d9d9d9',
                                borderRadius: '3px'
                            }}>
                                <Carousel autoplay draggable>
                                    {
                                        banner.map(v=> {
                                            return <div key={v}><img src={v} style={{width: "100%"}}/></div>
                                        })
                                    }
                                </Carousel>
                                <div className={styles.top}>
                                    <div id="title" className={styles.tit}>{getFieldValue('name')}</div>
                                    <div className={styles.desc} id="subTitle">{getFieldValue('desc')}</div>
                                    <div className={styles.price}>
                                        <div id="price" className={styles.num}>
                                            {
                                                specData.length == 0 ? getFieldValue('price') : minPrice
                                            }
                                            <span className={styles.lineprice}>
                                {getFieldValue('line_price')}
                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div className={styles.box} style={{marginTop: '10px', textAlign: 'center'}}>
                                    <img className={styles.logo} src={logo}/>
                                </div>
                                {
                                    paramsData.length > 0 ? <div className={styles.box} style={{marginTop: '10px'}}>
                                        <div className={styles.goodsintroduction}>
                                            <div className={styles.bar}>
                                                <div className={styles.tit}>商品参数</div>
                                            </div>
                                            <div className={styles.cont}>
                                                <div className={styles.paramstable}>
                                                    {
                                                        paramsData.map(item=> {
                                                            return <div className={styles.item}
                                                                        key={`params_${item.key}`}>
                                                                <div className={styles.key}>{item.key}：</div>
                                                                <div className={styles.value}>{item.value}</div>
                                                            </div>
                                                        })
                                                    }

                                                </div>
                                            </div>
                                        </div>
                                    </div> : null
                                }


                                <div className={styles.goodsdetail}>
                                    <div className={styles.goodsintroduction}>
                                        <div className={styles.bar}>
                                            <div className={styles.tit}>商品说明</div>
                                        </div>
                                        <div className={styles.cont} id="mainDesc"
                                             dangerouslySetInnerHTML={{__html: content}}>
                                        </div>
                                    </div>
                                </div>
                                <div className={styles.goods}>
                                    <div className={styles.indexbar}>
                                        <div className={styles.tit}>相关商品</div>
                                    </div>
                                    <div className={styles.goodslist}>
                                        {
                                            selectedGoods.length > 0 ?
                                                selectedGoods.map(item=> {
                                                    return <div className={styles.item} key={`relategoods_${item.id}`}>
                                                        <img src={item.imgs[0]} className={styles.pic}/>
                                                        <div className={styles.cont}>
                                                            <div className={styles.tit}>{item.name}</div>
                                                            <div className={styles.desc}>{item.desc}</div>
                                                            <div className={styles.foot}>
                                                                <div className={styles.price}>￥{item.min_price}</div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                })
                                                : null
                                        }
                                    </div>
                                </div>
                                {/*<div className={styles.h60}></div>*/}
                            </div>

                        </Col>
                        <Col md={17}>
                            <Form onSubmit={this.handleSubmit} style={{marginTop: 8}}>
                                <FormItem {...formItemLayout} label="商品名称">
                                    {getFieldDecorator('name', {
                                        initialValue: goods.name,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请给商品起个名字吧,128字内',
                                            },
                                        ],
                                    })(<Input placeholder="给商品起个名字吧"/>)}
                                </FormItem>
                                <FormItem {...formItemLayout} label="商品描述">
                                    {getFieldDecorator('desc', {
                                        initialValue: goods.desc,
                                        rules: [
                                            {
                                                message: '请输入对商品的描述',
                                            },
                                        ],
                                    })(
                                        <TextArea
                                            style={{minHeight: 32}}
                                            placeholder="请输入对商品的描述，字数不限"
                                            rows={4}
                                        />
                                    )}
                                </FormItem>
                                <FormItem {...formItemLayout} label="商品图片" help="最多上传15张 规格建议（800*800）,格式jpg,png,gif">
                                    {getFieldDecorator('imgs', {
                                        initialValue: imgsFileList,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请上传商品图片',
                                            },
                                        ],
                                    })(
                                        <Uploader
                                            length={15}
                                            fileList={imgsFileList}
                                            onChange={this.bindImgsChange}
                                        />
                                    )}
                                </FormItem>
                                <FormItem {...formItemLayout} label="商品类目">
                                    {getFieldDecorator('categoryId', {
                                        initialValue: goods.categoryId,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请给商品选个分类吧',
                                            },
                                        ],
                                    })(
                                        <Select placeholder="请选择所属行业类目" style={{width: '100%'}}
                                                onChange={this.bindCategoryChange}>
                                            {
                                                category.map(v=> {
                                                    return <Option value={v.id} key={v.id}>{v.name}</Option>
                                                })
                                            }
                                        </Select>
                                    )}
                                </FormItem>
                                <FormItem {...formItemLayout} label="商品分组">
                                    {getFieldDecorator('groups', {
                                        initialValue: goods.groups,
                                    })(
                                        <Select
                                            mode="multiple"
                                            style={{width: '100%'}}
                                            placeholder="Please select"
                                        >
                                            {
                                                group.map(v=> {
                                                    return <Option value={v.name} key={v.name}>{v.name}</Option>
                                                })
                                            }
                                        </Select>
                                    )}

                                    <GroupAdd dispatch={dispatch}/>
                                </FormItem>
                                <FormItem {...formItemLayout} label="主图视频" help={`建议时长9-30秒，建议视频宽高比16:9，以mp4格式为准`}>
                                    {getFieldDecorator('video', {})(
                                        <UploadVideo onChange={ this.bindVideoChange } fileList={ videoFileList }/>
                                    )}
                                </FormItem>
                                <Divider></Divider>
                                <FormItem {...formItemLayout} label="商品规格">
                                    <Spec onChange={this.bindSpcChange} defaultValue={specData}/>
                                </FormItem>
                                <FormItem {...formItemLayout} label="规格明细"
                                          style={{display: specData.length == 0 ? 'none' : 'block'}}>
                                    <SpecList data={specData} specList={goods.specs_list || []}
                                              onChange={this.bindSpecListChange} dispatch={dispatch}/>
                                </FormItem>
                                {
                                    specData.length == 0 ? <FormItem {...formItemLayout} label="价格">
                                        {getFieldDecorator('price', {
                                            initialValue: goods.price,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请填写统一商品价格',
                                                },
                                            ],
                                        })(<Input placeholder="统一商品价格"></Input>)}
                                    </FormItem> : null
                                }

                                <FormItem {...formItemLayout} label="划线价">
                                    {getFieldDecorator('line_price', {
                                        initialValue: goods.line_price,
                                    })(<Input placeholder="商品划线价格"></Input>)}
                                </FormItem>
                                {
                                    specData.length == 0 ? <div><FormItem {...formItemLayout} label="库存">
                                        {getFieldDecorator('stock', {
                                            initialValue: goods.stock,
                                            rules: [{
                                                required: true,
                                                message: '请填写商品库存'
                                            }]
                                        })(<Input placeholder="0"></Input>)}
                                    </FormItem><FormItem {...formItemLayout} label="供货价">
                                        {getFieldDecorator('settlement_price', {
                                            initialValue: goods.settlement_price,
                                            rules: [{
                                                required: true,
                                                message: '请填写商品供货价'
                                            }]
                                        })(<Input placeholder="0"></Input>)}
                                    </FormItem></div> : null
                                }

                                {/*<FormItem {...formItemLayout} label="快递运费">
                                 {getFieldDecorator('express', {
                                 initialValue: goods.express,
                                 rules: [
                                 {
                                 required: true,
                                 message: '请填写快递运费',
                                 },
                                 ],
                                 })(<Input placeholder="0"></Input>)}
                                 </FormItem>*/}
                                <FormItem {...formItemLayout} label="上架状态">
                                    {
                                        getFieldDecorator('status', {
                                          // 商品状态：管理员新增，默认为上架、修改默认为当前状态
                                          //          商家新增，默认为提交审核、修改默认也为提交审核
                                            initialValue: getAuthority() == 'admin' ? (goods.status || 1 ): 3,
                                        })(
                                            <Radio.Group>
                                                <Authorized authority="admin">
                                                    <Radio value={1}>立即上架</Radio>
                                                </Authorized>
                                                <Authorized authority="business">
                                                    <Radio value={3}>申请上架，等待审核</Radio>
                                                </Authorized>
                                                <Radio value={0}>暂不售卖，放入仓库</Radio>
                                            </Radio.Group>
                                        )
                                    }
                                </FormItem>
                                <FormItem {...formItemLayout} label="相关商品类型">
                                    {
                                        getFieldDecorator('link_goods', {
                                            initialValue: goods.link_info.model || 0,
                                        })(
                                            <Select onSelect={this.bindLinkGoods} onChange={this.bindChangeLinkGoods}>
                                                <Option value={0}>同类商品</Option>
                                                <Option value={1}>最新商品</Option>
                                                <Option value={2}>最热商品</Option>
                                                <Option value={3}>手动选择</Option>
                                                <Option value={-1}>不显示</Option>
                                            </Select>
                                        )
                                    }
                                    <div className="ant-form-explain">{
                                        linkGoodsTip[getFieldValue('link_goods')]
                                    }</div>
                                    {
                                        selectedGoods.length > 0 ? <Table
                                            style={{marginTop: '8px'}}
                                            pagination={false}
                                            columns={columns}
                                            dataSource={selectedGoods}
                                            rowKey="id"
                                        ></Table> : '暂无相关商品'
                                    }

                                </FormItem>
                                <Divider />
                                <Authorized authority="admin">
                                    <FormItem {...formItemLayout} label="排序权重"  help={`0-99，默认0，值越大，商品排序越靠前`}>
                                        {getFieldDecorator('order_weight', {
                                            initialValue: (goods.order_weight || 0),
                                        })(<Input placeholder="请输入0-99的任一值"></Input>)}
                                    </FormItem>
                                </Authorized>
                                <FormItem {...formItemLayout} label="规格参数">
                                    <SpecParams onChange={this.bindSpecParamsChange} data={paramsData}/>
                                </FormItem>
                            </Form>
                            <FormItem {...formDetailItemLayout} label="详情">
                                <MyEditor onChange={this.bindMyEditorChange} value={content} defaultValue={content}/>
                            </FormItem>
                            <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                                {/*<Button type="primary" htmlType="submit" loading={submitting}>
                                 提交
                                 </Button>*/}
                                <Button type="primary" loading={false} onClick={this.handleSubmit}>
                                    提交
                                </Button>
                                <Button style={{marginLeft: 8}}><Link to={`/goods/goods-list`}>返回</Link></Button>
                            </FormItem>
                        </Col>
                    </Row>
                </Card>
                <GoodsModal
                    type="coupon"
                    dispatch={this.props.dispatch}
                    modalVisible={modalVisible}
                    handleHide={this.handleModalVisible}
                    selectedRows={selectedGoods}
                    changeSelectedGoods={this.changeSelectedGoods}
                />
            </div>
        );
    }
}
